// console.log("main.js 入口文件");

// https://www.npmjs.com/package/commander
const { program } = require("commander");
const { version } = require("./constants");
const path = require("path");

// console.log(process.argv);
// [
//   'C:\\Program Files\\nodejs\\node.exe',
//   'C:\\Program Files\\nodejs\\node_modules\\why-cli\\bin\\www',
//   'create',
//   'vue'
// ]

// 命令集合
const mapCommands = {
  create: {
    alias: "c",
    description: "create a project",
    examples: ["why-cli create <project-name>"],
  },
  config: {
    alias: "conf",
    description: "configs of project",
    examples: ["why-cli config set <k> <v>", "why-cli config get <k>"],
  },
  "*": {
    alias: "",
    description: "not found command",
    examples: [],
  },
};

// 生成命令
Reflect.ownKeys(mapCommands).forEach((command) => {
  program
    .command(command) // 命令名称
    .alias(mapCommands[command].alias) // 命令别名
    .description(mapCommands[command].description) // 该命令的描述信息
    .action(() => {
      // 执行该命令的回调
      if (command === "*") {
        // 找不到命令
        console.log(mapCommands[command].description);
      } else {
        // console.log(command);
        // 执行对应命令的逻辑
        // process.argv.slice(3)  截取项目名称，例如：why-cli create project-name 这条命令中的 project-name
        require(path.resolve(__dirname, command))(process.argv.slice(3));
      }
    });
});

// 监听 --help 命令，命令行窗口打印每个命令 example
program.on("--help", () => {
  console.log("\nExamples:");
  Reflect.ownKeys(mapCommands).forEach((command) => {
    mapCommands[command].examples.forEach((example) => {
      console.log(`  ${example}`);
    });
  });
});

// version
program.version(version).parse(process.argv);
